<?php

namespace app\shop\controller\product;

use app\common\model\product\Category;
use app\Request;
use app\shop\controller\Controller;
use app\shop\model\product\ProductTemplateModel;

/**
 * 商品模板管理控制器
 */
class ProductTemplate extends Controller
{
    public function createData(Request $request)
    {
        $where = $request->param();
        $list = ProductTemplateModel::listAll(['product_id' => $where['product_id']]);
        if (count($list) > 0) return $this->renderError('该商品已保存模版');
        ProductTemplateModel::createData($where);
        return $this->renderSuccess();
    }

    public function listData(Request $request)
    {
        $where = $request->param();
        $getname = '';
        if(isset($where['name'])){
            $getname = $where['name'];
            unset($where['name']);
        }
        $category_list = (new Category()) -> column('name','category_id');
        $list = ProductTemplateModel::listData($where, $this->getData(), ['product' => function ($query) {
            $query->with(['image.file','category']);
        }],'a.id asc',['product p','p.product_name like "%'.$getname.'%" and p.product_id=a.product_id']);

        // 商品分类
        $category = Category::getCacheTree();
        foreach ($list as $key => $value){
            $category_child_name = $category_list[$value['category']['category_id']]??'';
            $category_parent_name = $category_list[$value['category']['parent_id']]??'';
            $list[$key]['category_name_text'] = $category_parent_name ?$category_parent_name.'-'.$category_child_name:$category_child_name;
        }

        return $this->renderSuccess('', compact('list', 'category'));
    }

    public function deleteData(Request $request)
    {
        $where = $request->param();
        $one = ProductTemplateModel::one($where);
        $one->delete();
        return $this->renderSuccess('删除成功');
    }

    public function editShow(Request $request)
    {
        $where = $request->param();
        $one = ProductTemplateModel::one($where);
        if ($one['is_show'] == 0) {
            $one['is_show'] = 1;
            $one->save();
        } else {
            $one['is_show'] = 0;
            $one->save();
        }
        return $this->renderSuccess('操作成功');
    }
}
